package com.boil.qz.safekavass.repository;

import com.boil.qz.safekavass.model.ResourceEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * Created by ChenYong on 2017-07-11.
 * <br>
 * 资源实体仓库。
 */
public interface ResourceRepository extends JpaRepository<ResourceEntity, Long> {
    /**
     * 根据资源编号 <code>List</code> 查询资源实例 <code>List</code>。
     *
     * @param ids 资源编号 <code>List</code>
     * @return 资源实例 <code>List</code>
     */
    @Query(value = "select resource from ResourceEntity resource where resource.deletedCode = 0 and resource.id in ?1")
    public List<ResourceEntity> findByIds(List<Long> ids);

    /**
     * 根据父编号和资源类型查询资源。
     *
     * @param parentId     父编号
     * @param resourceType 资源类型
     * @return 资源实例 <code>List</code>
     */
    @Query(value = "select resource from ResourceEntity resource where resource.parent.id = ?1 and resource.resourceType = ?2")
    public List<ResourceEntity> findByParentIdAndResourceType(long parentId, int resourceType);

    /**
     * 根据删除代码查询资源。
     *
     * @param deletedCode 删除代码
     * @return 资源实例 <code>List</code>
     */
    public List<ResourceEntity> findByDeletedCode(int deletedCode);

    /**
     * 根据资源类型和用户 ID 查询资源。
     *
     * @param resourceType 资源类型
     * @param userId       用户 ID
     * @return 资源实例 <code>List</code>
     */
    @Query(value = "SELECT DISTINCT T3.* " +
            "FROM TB_LOGIN_USERS T1, TB_QZ_ROLE T2, TB_QZ_RESOURCE T3, TB_QZ_USER_ROLE T4, TB_QZ_ROLE_RESOURCE T5 " +
            "WHERE T1.ID = T4.USER_ID " +
            "AND T2.ID = T4.ROLE_ID " +
            "AND T2.ID = T5.ROLE_ID " +
            "AND T3.ID = T5.RESOURCE_ID " +
            "AND T3.RESOURCE_TYPE = ?1 " +
            "AND T3.DELETED_CODE = 0 " +
            "AND T1.ID = ?2 " +
            "ORDER BY T3.RESOURCE_LEVEL ASC, T3.RESOURCE_ORDER ASC", nativeQuery = true)
    public List<ResourceEntity> findByResourceTypeAndUserId(int resourceType, long userId);

    /**
     * 根据权限代码统计资源个数。
     *
     * @param permissionCode 权限代码
     * @return 资源个数
     */
    @Query(value = "select count(resource) from ResourceEntity resource where resource.deletedCode = 0 and resource.permissionCode = ?1")
    public long countByPermissionCode(String permissionCode);

    /**
     * 根据资源 URL 统计资源个数。
     *
     * @param resourceUrl 资源 URL
     * @return 资源个数
     */
    @Query(value = "select count(resource) from ResourceEntity resource where resource.deletedCode = 0 and resource.resourceUrl = ?1")
    public long countByResourceUrl(String resourceUrl);
}